<template>
  <div>
    <!-- 导航内容 -->
    <div class="task-tag-list-container" ref="taskTagListRef">
      <ul class="task-tag-list">
        <li
          v-for="item in taskTagList"
          :key="item"
          @click="changeTaskTag(item)"
          :class="{
            'task-tag-item': true,
            active: item === currentTagItem
          }"
        >{{ item }}</li>
      </ul>
    </div>
    <!-- 滚动内容 -->
    <div class="task-detail" ref="taskDetailContainerRef">
      <div v-for="(taskItem, TaskIndex) in list" :key="taskItem.id">
        <div
          class="building-name"
          :ref="taskItem.storey + 'ref'"
          v-if="TaskIndex == 0 || list[TaskIndex - 1].storey != list[TaskIndex].storey"
        >{{ taskItem.storey }}</div>
        <div class="task-detail-item-container">
          <div class="title">内容，有交互，不定高度</div>
          <div>{{taskItem}}</div>
          <img :src="taskItem.image" alt="随机图片" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// import { throttle } from "../utils/index.js";
import { throttle } from "lodash-es";
import axios from "axios";
export default {
  name: "ScrollPage",
  data() {
    return {
      currentTagItem: "楼层",
      currentTagNextItem: "",
      currentTagPrevItem: "",
      list: []
    };
  },
  computed: {
    taskTagList() {
      let cloneData = JSON.parse(JSON.stringify(this.list));
      cloneData = cloneData.map(father => {
        return father.storey;
      });
      cloneData = [...new Set(cloneData)];
      return cloneData;
    }
  },
  mounted() {
    axios
      .get("/api/building")
      .then(({ data }) => {
        console.log("data", JSON.stringify(data));
        this.list = data.data.sort((a, b) => {
          return a.storey - b.storey;
        });
        window.addEventListener("scroll", throttle(this.handleScroll, 16));
      })
      .catch(err => {
        console.log("接口请求出错", err);
      })
      .finally(() => {
        this.currentTagItem = this.taskTagList[0];
      });
  },
  beforeDestroy() {
    window.removeEventListener("scroll", throttle(this.handleScroll, 16));
  },
  methods: {
    handleScroll() {
      const scrollTop = window.scrollY;
      // 处理滚动位置
      let list = this.taskTagList;
      if (Array.isArray(list)) {
        let nextTagValue = list[list.length - 1];
        let prevTagValue = list[0];
        list.forEach((tagItem, index) => {
          if (tagItem == this.currentTagItem && index < list.length - 1) {
            nextTagValue = list[index + 1];
          }
          if (tagItem == this.currentTagItem && index > 0) {
            prevTagValue = list[index - 1];
          }
        });
        this.currentTagNextItem = nextTagValue;
        this.currentTagPrevItem = prevTagValue;
      }
      try {
        if (
          scrollTop + this.$refs["taskTagListRef"].offsetHeight + 16 >=
          this.$refs[this.currentTagNextItem + "ref"][0].offsetTop
        ) {
          this.currentTagItem = this.currentTagNextItem;
        } else {
          if (
            scrollTop + this.$refs["taskTagListRef"].offsetHeight + 16 <
            this.$refs[this.currentTagItem + "ref"][0].offsetTop
          ) {
            this.currentTagItem = this.currentTagPrevItem;
          }
        }
      } catch (err) {
        console.log("页面还没渲染元素taskTagListRef", err);
      }
    },
    changeTaskTag(item) {
      let scrollDistance =
        this.$refs[item + "ref"][0].offsetTop -
        this.$refs["taskTagListRef"].offsetHeight -
        16;
      try {
        window.scrollTo({
          left: 0,
          top: scrollDistance,
          behavior: "smooth"
        });
      } catch (err) {
        console.log("低版本api兼容", err);
        window.scrollTo(0, scrollDistance);
      }
    }
  }
};
</script>

<style scoped lang="scss">
.task-tag-list-container {
  position: sticky;
  top: 0;
  left: 0;
  z-index: 5;
  background-color: #fff;
  border-bottom: 1px solid #a3a3a3;
  overflow-x: scroll;
  .task-tag-list {
    display: flex;
    padding: 16px;
    min-width: calc(100vw - 64px);
    > li {
      list-style-type: none;
      margin: 8px;
      font-size: 16px;
      white-space: nowrap;
      cursor: pointer;
      text-align: center;
    }

    .active {
      font-weight: bold;
      color: #2a2b32;
      &::after {
        content: "";
        display: block;
        text-align: center;
        width: 18px;
        height: 4px;
        border-radius: 4px;
        background-color: #ffd333;
        margin: 0 auto;
        margin-top: 4px;
      }
    }
  }
}
.task-detail {
  margin: 16px;
  .building-name {
    margin-top: 16px;
    margin-bottom: 16px;
    font-weight: bold;
  }
  .task-detail-item-container {
    margin-top: 16px;
    height: 200px;
    border-radius: 8px;
    border: 1px solid #a3a3a3;
    padding: 16px;
    .title {
      font-weight: bold;
      margin-bottom: 16px;
    }
  }
}
</style>